package com.yixing.demo.controller;
import com.yixing.demo.component.JwtClass;
import com.yixing.demo.constants.Constants;
import com.yixing.demo.model.User;
import com.yixing.demo.service.UserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.dao.DuplicateKeyException;
import org.springframework.http.ResponseEntity;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

@Slf4j
@RestController
@RequestMapping("/user")
public class UserController {
    //不能加static修饰，否则配置文件的内容注入不进来
    private String SAVE_PATH = "D:/chat_in_different_dimensions_practice/";
    @Resource
    UserService userService;
    @Resource
    BCryptPasswordEncoder bCryptPasswordEncoder;

    @RequestMapping("/login")
    public User login(String username, String password, HttpSession session) {
        if(!StringUtils.hasLength(username) || !StringUtils.hasLength(password)) {
            log.info("用户名或密码不能为空");
            return new User();
        }
        User userInfo = userService.login(username);
        if(userInfo == null) {
            log.info("用户名或密码错误");
            return new User();
        }else {
            if(bCryptPasswordEncoder.matches(password, userInfo.getPassword())) {
                Map<String, Object> map = new HashMap<>();
                map.put(Constants.USER_ID, userInfo.getUserId());
                map.put(Constants.USER_NAME, userInfo.getUsername());
                String token = JwtClass.getToken(map);
                session.setAttribute(Constants.USER_SESSION, userInfo);
                userInfo.setToken(token);
                userInfo.setPassword("");
                return userInfo;
            }else {
                log.info("用户名或密码错误");
                return new User();
            }
        }
    }

    @RequestMapping("/register")
    public User register(User user) {
       String encoderPassword = bCryptPasswordEncoder.encode(user.getPassword());
       user.setPassword(encoderPassword);
       try {
           userService.register(user);
       } catch (DuplicateKeyException e) {
          log.info("用户注册失败");
          return new User();
       }
       user.setPassword("");
       return user;
    }

    @RequestMapping("/getuserInfo")
    public User getuserInfo(HttpServletRequest req) {
        HttpSession session = req.getSession(false);
        if(session == null) {
            log.info("获取不到session对象");
            return new User();
        }
        User userInfo = (User)session.getAttribute(Constants.USER_SESSION);
        if(userInfo == null) {
            log.info("在session中获取不到user对象");
            return new User();
        }
        userInfo.setPassword("");
        return userInfo;
    }


    @RequestMapping("/upload")
    public Object upload(MultipartFile file, HttpServletRequest req) {
        String titleAndType = file.getOriginalFilename();
        if(titleAndType.equals("")) {
            return false;
        }
        String localFilePath = SAVE_PATH + titleAndType;
        System.out.println(localFilePath);
        File localFile = new File(localFilePath);
        if (!localFile.exists()) {
            localFile.mkdirs();
        }
        try {
            file.transferTo(localFile);
        } catch (IOException e) {
            e.printStackTrace();
            return false;
        }
        HttpSession session = req.getSession(false);
        User userInfo = (User) session.getAttribute(Constants.USER_SESSION);
        try {
            userService.uploadAvatar(localFilePath, userInfo.getUserId());
            return true;
        } catch (Exception e) {
            e.printStackTrace();
            localFile.delete();//这一步一定要写
            return false;
        }
    }

    @RequestMapping("/getavatar")
    public ResponseEntity<byte[]> play(String username, HttpServletRequest req) {
        if(username == null) {
            HttpSession session = req.getSession(false);
            User userInfo = (User)session.getAttribute(Constants.USER_SESSION);
            String avatarPath = userService.selectAvatar(userInfo.getUserId());
            if(avatarPath == null) {
                return null;
            }else {
                try {
                    byte[] bytes = Files.readAllBytes(new File(avatarPath).toPath());
                    return ResponseEntity.ok(bytes);
                } catch (IOException e) {
                    e.printStackTrace();
                    return null;//这个返回一定要有
                }
            }
        }else {
            String avatarPath = userService.selectAvatarByUsername(username);
            if(avatarPath == null) {
                return null;
            }else {
                try {
                    byte[] bytes = Files.readAllBytes(new File(avatarPath).toPath());
                    return ResponseEntity.ok(bytes);
                } catch (IOException e) {
                    e.printStackTrace();
                    return null;//这个返回一定要有
                }
            }
        }
    }
}
